<?php

namespace App\Http\Controllers\Api;

use App\Models\Currency;
use App\Models\Property;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Turn;
use App\Models\Wallet;
use App\Models\User;
use App\Models\Config;
use Exception;
use DB;
use App\Library\BTC\BitcoinFunction;
use App\Library\ETH\EthereumFunction;
use App\Library\OBA\ObaFunction;
use App\Library\Orders\Orders;
use App\Library\Orders\Turns;

/**
 * 转入转出.
 */
class TurnController extends Controller
{
    /**
     * 转入转出列表
     *
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/3/17
     * @access public
     * @param  int    uid    用户ID
     * @return array        记录列表
     */
    public function turn_list(Request $request)
    {
        $info  = $request->all();
        $currency_model = new Currency();
        if (empty($info['uid'])||empty($info['page'])||empty($info['type'])||empty($info['cid']))
            return respF(1003);
        $uid = $info['uid'];
        $cid = $info['cid'];
        $page = $info['page']-1;
        $type = $info['type'];
        if (!in_array($type,[1,2]))
            return respF(1003);
        if ($page < 0)
            return respF(1022);
        $currency = $currency_model->where('id',$cid)->select('out_value','into_value')->first();

        $where['uid'] = $uid;
        $where['type'] = $type;
        $where['cid'] = $cid;
        if ($type==1){
            $turns = Turn::where($where)->where('num','>=',$currency['into_value'])->orderby('id','DESC')->paginate(10);

        }else{
            $turns = Turn::where($where)->where('num','>=',$currency['out_value'])->orderby('id','DESC')->paginate(10);

        }
        if (collect($turns)->count() == 0) {
            return respF(1022);
        }else{
            //处理数据
            $data = [];
            foreach ($turns as $key => $val) {
                $data[$key]['cid'] = $val->cid;
                $data[$key]['c_name'] = $val->currency->name_en;
                $data[$key]['logo'] = config('alioss.host') . '/' . $val->currency->logo;
                $data[$key]['num'] = $val->num;
                $data[$key]['status'] = $val->status;
                $data[$key]['type'] = $val->type;
                $data[$key]['created_at'] = $val->updated_at->format('Y-m-d H:i:s');
            }
            $data = array_merge($data);
            if (collect($data)->count() == 0)
                return respF(1022);
            $list['status'] = 1;
            $list['msg'] = '查询成功';
            $list['data'] = $data;
        }
        return response()->json($list);
    }


    /**
     * 转入页面显示
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/5/24
     * @access public|private|protected
     * @param  mixed    name    comment
     * @param  int    name    comment
     * @param  string    name    comment
     * @param  bool       name    comment
     * @param  array   name    comment
     * @return void|int|string|boolean|array        comment
     */
    public function turn_into(Request $request){
        $info = $request->all();
        if (empty($info['cid'])||empty($info['uid']))
            return respF(1000);
        $uid = $info['uid'];
        $cid = $info['cid'];
        $model = new Orders();
        $tuans_model = new Turns();
        $currency = $model->currency_verify($cid);
        if (!$currency)
            return respF(1000);
        $c_name = $currency->name_en;
        if (!in_array($c_name,config('config.roll')))
            return respF(2031);
        //查询资产
        $property =$model->property_verif($uid,$cid);
        if (!$property)
            return respF(1000);
        $list['c_name'] = $c_name;
        $list['into_fee'] = $currency->into_fee;
        $list['into_value'] = $currency->into_value;
        $list['balance'] = $property->balance;
        $list['blocked'] = $property->blocked;
        $string = Config::where('key','into_instructions')->first()->value;
        $list['note'] = vsprintf($string,[$currency->into_value.$c_name]);
        $map['cid'] = $cid;
        $map['uid'] = $uid;
        $map['status'] = 1;
        $map['type'] = 1;
        $wallet = Turn::where($map)->where('trade_time','>',time())->first();
        if ($wallet) {
            $list['address'] = $wallet->wallet_address;
        } else {
            $tuans = $tuans_model->into($uid,$cid,$c_name);
            if (!$tuans||$tuans==false){
                return respF(1018);
            }else{
                $list['address'] = $tuans;
            }
        }
        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $list]);
    }

    /**
     * 转出页面
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/5/17
     * @access public
     * @param  int    cid    comment
     * @param  int    uid    comment
     * @return json
     */
    public function turn_out(Request $request){
        $info = $request->all();
        if (empty($info['cid'])||empty($info['uid']))
            return respF(1000);
        $uid = $info['uid'];
        $cid = $info['cid'];
        $model = new Orders();
        $currency = $model->currency_verify($cid);
        if (!$currency)
            return respF(1000);
        $c_name = $currency->name_en;
        if (!in_array($c_name,config('config.roll')))
            return respF(2031);
        //查询资产
        $property =$model->property_verif($uid,$cid);
        if (!$property)
            return respF(1000);
        $list['c_name'] = $c_name;
        $list['out_fee'] = $currency->out_fee;
        $list['out_value'] = $currency->out_value;
        $list['balance'] = $property->balance;
        $list['blocked'] = $property->blocked;
        $string = Config::where('key','out_instructions')->first()->value;
        $list['note'] = vsprintf($string,[$currency->out_value.$c_name,$currency->out_fee.'%'.$c_name]);
        //限制最小值
        switch ($c_name){
            case 'OBA' :
                $list['num'] = 1;
                break;
            case 'BTC' :
                $list['num'] = 0.001;
                break;
            case 'ETH' :
                $list['num'] = 0.01;
                break;
            case 'LTC' :
                $list['num'] = 0.1;
                break;
            case 'TRX' :
            case 'DOGE' :
                $list['num'] = 20;
                break;
        }
        $list['unit'] = 4;
        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $list]);

    }
    /**
     * 转出提交
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/4/9
     * @access public|private|protected
     * @param  mixed    name    comment
     * @param  int    name    comment
     * @param  string    name    comment
     * @param  bool       name    comment
     * @param  array   name    comment
     * @return void|int|string|boolean|array        comment
     */
    public function turn_out_submit(Request $request)
    {
        $info = $request->all();
        if (empty($info['address'])||empty($info['cid'])||empty($info['uid'])||empty($info['psd'])||empty($info['num']))
            return respF(1000);
        $model = new Orders();
        $currency = $model->currency_verify($info['cid']);
        if ((float)$currency->out_value > (float)$info['num'])
            return respF(1039);

        if ($currency->max_quota < (float)$info['num'])
            return respF(1044);
        //验证密码
        $where_u['id'] = $info['uid'];
        $user_info = User::where($where_u)->first();
        if (empty($user_info['pay_pass']))
            return respF(1040);
        if ($user_info['pay_pass'] != md5($info['psd']))
            return respF(1038);
        //验证钱
        $property_u = $model->property_verif($info['uid'],$info['cid']);
        if (!$property_u||(float)$info['num'] > (float)$property_u->balance)
            return respF(1036);


        //验证地址
        $currency = Currency::where('id',$info['cid'])->first();
        if (!$currency)
            return respF(1037);
        $c_name = $currency->name_en;
        switch ($c_name){
            case 'BTC':
            case  'LTC':
            case  'DGC':
                $btc_model = new BitcoinFunction($c_name);
                $re_m = $btc_model->addressValidator($info['address']);
                break;
            case 'ETH':
                $etc_model = new EthereumFunction();
                $re_m = $etc_model->addressValidator($info['address']);
                break;
            case 'OBA':
                $oba_model = new ObaFunction();
                //$re_m = $oba_model->getBalanceByAddress($info['address']);
                $re_m = $oba_model->addressValidator($info['address']);
                break;
            default:
                return respF(2031);
        }
        //dd($re_m);
        if (!$re_m)
            return respF(1037);
        $add_now = Wallet::where('address',$info['address'])->first();
        if ($add_now)
            return respF(1043);
        //计算手续费
        $data1['uid'] = $info['uid'];
        $data1['cid'] = $info['cid'];
        $data1['wallet_address'] = $info['address'];
        $data1['num'] = (float)$info['num'];
        $data1['proc'] = bcdiv(bcmul($currency->out_fee,$data1['num'],8),100,8);
        $data1['real_num'] =  bcsub($data1['num'],$data1['proc'],8);
        $data1['type'] = 2;
        $data1['status'] = 1;
        $data1['trade_time'] = time()+60*60*2;
        $data1['unlock_time'] = $data1['trade_time']+60*60*6;
        $data1['order_no'] = get_microtimes();
        try {
            DB::beginTransaction();
            Turn::create($data1);
            $property_u->decrement('balance',(float)$info['num']);
            $property_u->increment('blocked',(float)$info['num']);
            DB::commit();
            return response()->json(['status' => 1, 'msg' => '提交成功']);
        } catch (Exception $e) {
            DB::rollback();
            return respF(1018);
        }
    }
}
